package com.richper.springcloudh2020.controller;

import com.richper.springcloudh2020.entities.CommonResult;
import com.richper.springcloudh2020.entities.Payment;
import com.richper.springcloudh2020.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private DiscoveryClient discoveryClient;


    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/insertPayMent")
    @ResponseBody
    public CommonResult insertPayMent(@RequestBody Payment payment){
        if (payment == null) {
            return new CommonResult(444,"参数为空",null);
        }
        int insCount = paymentService.insertPayMent(payment);
        log.info("insertPayMent插入结果集>>>"+insCount);
        if(insCount > 0){
            return new CommonResult(200,serverPort+" 成功啦！太好啦~",insCount);
        }else {
            return new CommonResult(444,"失败啦！怎么办啦~",null);
        }
    }

    @GetMapping(value = "/queryPayMentByID/{id}")
    @ResponseBody
    public CommonResult queryPayMentByID(@PathVariable Long id){
        if (id == null) {
            return new CommonResult(444,"参数为空",null);
        }
        Payment payment = paymentService.queryPayMentByID(id);
        log.info("queryPayMentByID查询结果集>>>"+payment);
        if(payment != null){
            return new CommonResult(200,serverPort+" 成功啦！太好啦~",payment);
        }else {
            return new CommonResult(444,"失败啦！怎么办啦~",null);
        }
    }

    @GetMapping("discovery")
    @ResponseBody
    public Object discovery(){
        List<ServiceInstance> instances = this.discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        return new CommonResult<List<ServiceInstance>>(200,"8002暴露服务信息",instances);
    }

    @RequestMapping("/lb/getPort")
    @ResponseBody
    public String getPort(){
        return serverPort;
    }

    @RequestMapping("/feignTimeOutDemo")
    @ResponseBody
    public String feignTimeOutDemo(){
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
